package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    //批量添加
    public void add(List<OrderSetting> list) {
        if (list!=null && list.size()>0){
            for (OrderSetting orderSetting : list) {
                //检查此数据（日期）是否存在
               long count =  orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
               if (count > 0){
                   //已经存在，执行更新操作
                   orderSettingDao.editNumberByOrderDate(orderSetting);
               } else {
                   //不存在，执行添加操作
                   orderSettingDao.add(orderSetting);
               }
            }
        }
    }

    //根据日期查询预约设置数据
    public List<Map> getOrderSettingByMonth(String date) {
        String dateBegin = date + "-1";
        String dateEnd = date + "-31";
        Map map = new HashMap<>();
        map.put("dateBegin",dateBegin);
        map.put("dateEnd",dateEnd);
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);
        List<Map> result = new ArrayList<>();
        for (OrderSetting orderSetting : list) {
            Map orderSettingMap = new HashMap();
            orderSettingMap.put("date",orderSetting.getOrderDate().getDate());//获得日期（几号）
            orderSettingMap.put("number",orderSetting.getNumber());//可预约人数
            orderSettingMap.put("reservations",orderSetting.getReservations());//已预约人数
            result.add(orderSettingMap);
        }

        return result;
    }

    //根据日期修改可预约人数
    public void editNumberByDate(OrderSetting orderSetting) {
        long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (count > 0){
            //当前日期已经进行了预约设置， 需要进行修改操作
            orderSettingDao.editNumberByOrderDate(orderSetting);
        } else {
            //当前日期没有进行预约设置， 进行添加操作
            orderSettingDao.add(orderSetting);
        }
    }

    @Override
    //分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) throws Exception {
        //从条件对象中获取参数
        Integer currentPage = queryPageBean.getCurrentPage(); // 页码
        Integer pageSize = queryPageBean.getPageSize(); // 每页显示的条数
        String queryString = queryPageBean.getQueryString(); //查询条件
        PageHelper.startPage(currentPage,pageSize);
        List<Map> list=orderSettingDao.findByCondition(queryString);
        for (Map map : list) {
            Date orderDate = (Date) map.get("orderDate");
            String orderDates = DateUtils.parseDate2String(orderDate);
            map.put("orderDates",orderDates);
        }
        PageInfo<Map> permissionPageInfo = new PageInfo<>(list);
        long total = permissionPageInfo.getTotal();
        List<Map> list1 = permissionPageInfo.getList();
        return new PageResult(total,list1);
    }

    @Override
    //删除
    public void delete(Integer id) {
       Member member= orderSettingDao.findMemberByOrderId(id);
       if (member!=null) {
           //将order的member_id设置为空
           orderSettingDao.updateOrderMember_idIsNull(id);
       }
           //删除
           orderSettingDao.deleteById(id);
           //删除后发送信息
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,member.getPhoneNumber(),"11111");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("=======================================>发送失败");
        }
        System.out.println("=============================================>短信已经发送");

    }

    @Override
    public Result findByOrderDate(Date orderDate) {
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(orderDate);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //检查预约日期是否已满
        int number = orderSetting.getNumber();//获取可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number){
            //预约已满， 不能预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        return new Result(true,MessageConstant.SELECTED_DATE_CAN_ORDER);
    }
}
